package com.dhcc.jparw.service.impl;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dhcc.jparw.config.DataSourceConfig;
import com.dhcc.jparw.config.annotation.DynamicSwitchDataSource;
import com.dhcc.jparw.dao.StudentDao;
import com.dhcc.jparw.entity.Student;
import com.dhcc.jparw.service.StudentService;

@Service
public class StudentServiceImpl implements StudentService {

  @Autowired
  private StudentDao studentDao;

  @Override
  @DynamicSwitchDataSource(dataSource = DataSourceConfig.READ_DATASOURCE_KEY)
  public List<Student> findAll() {
    return studentDao.findAll();
  }

  @Override
  @DynamicSwitchDataSource(dataSource = DataSourceConfig.READ_DATASOURCE_KEY)
  public Student findById(Integer id) {
    Optional<Student> students = studentDao.findById(id);
    if (students.isPresent() && students.get() != null) {
      return students.get();
    }
    return null;
  }

  @Override
  @Transactional
  @DynamicSwitchDataSource(dataSource = DataSourceConfig.WRITE_DATASOURCE_KEY)
  public Integer save(Student entity) throws Exception {
    if (entity.getId() != null) {
      Student perz = studentDao.saveAndFlush(entity);
      return perz.getId();
    }
    Student perz = studentDao.save(entity);
    return perz.getId();
  }

}
